package com.zrb.mobile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.hhpm.lib.banner.BGABanner;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.zrb.applib.utils.AppSetting;
import com.zrb.discover.Dynamic_banner_fragment;
import com.zrb.mobile.adapter.Discover_listAdapter;
import com.zrb.mobile.adapter.Discover_listAdapter.onActionlistener;
import com.zrb.mobile.adapter.RecImgpagerAdapter;
import com.zrb.mobile.adapter.model.AdsDto;
import com.zrb.mobile.adapter.model.AdsDtoResult;
import com.zrb.mobile.adapter.model.DynamicDto;
import com.zrb.mobile.adapter.model.DynamicDtos;
import com.zrb.mobile.adapter.scrollInterfaceImpl.DiscoverListViewScrollListenerImpl;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.PullToRefreshListViewEx;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CollectionHelper.onCollectionListener;
import com.zrb.mobile.utility.AlertDialog;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.TimeUtil;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Discover_MainFragment extends Fragment implements onLoadMoreListener , onActionlistener, onCollectionListener {
	private static final String LOG_TAG = "Discover_MainFragment";
	PullToRefreshListViewEx msearchResults;
	Discover_listAdapter mAdapter2;
	int currentPage;
	Handler mhandler = new Handler();
	boolean isFirstIn = true;
	// public String ACTION_NAME = "discover_main";
	// public String ACTION_NAME_ONE = "discover_content";
	private Dialog PopDialog;
	private TextView mTmptitle;
	private String mFindStr = "";
	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	 RecImgpagerAdapter mbannerAdapter;
	 BGABanner mGABanner;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 		View view = inflater.inflate(R.layout.discover_mainfragment, container, false);
		 
		mTmptitle = (TextView) view.findViewById(R.id.titleText);
		mFindStr = getResources().getString(R.string.menu_discover);
		mTmptitle.setText(mFindStr);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		msearchResults = (PullToRefreshListViewEx) this.getView().findViewById(R.id.discover_list_view);
		msearchResults.setPagesize(10);
		// Set a listener to be invoked when the list should be refreshed.
		msearchResults.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(CommonUtil.getcurTime(getActivity()));
				currentPage = 1;
				mhandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						LoadData(-1, true);
					}
				}, 1000);
			}
		});

		
		if(isFirstIn){
			   LayoutInflater inflater = LayoutInflater.from(this.getActivity());
		        View  _bannerView = inflater.inflate(R.layout.dynamic_banner_fragment, null); 
		         // mXListView.removeHeaderView(v)
		   		ListView actualListView= msearchResults.getRefreshableView();
		   		actualListView.addHeaderView(_bannerView);
 		}
 
     	 
		mAdapter2 = new Discover_listAdapter(getActivity());
	 
		msearchResults.initAdapter(mAdapter2);
		mAdapter2.setOnAction(this);
		msearchResults.setOnLoadMoreListener(this);
		msearchResults.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Intent intent;
				DynamicDto tmpDto = mAdapter2.mCurrentDatas.get(position - 1);
				// if (tmpDto.projectId == null) {
				// intent = new Intent(getActivity(),
				// DiscoverDetailOneActivity.class);
				// intent.putExtra("attention", tmpDto.attention);
				// intent.putExtra("id", tmpDto.id);
				// intent.putExtra("type", tmpDto.type);
				// intent.putExtra("attentionTimes", tmpDto.attentionTimes);
				// intent.putExtra("messageAmount", tmpDto.messageAmount);
				// intent.putExtra("position", position - 1);
				// intent.putExtra("from", "1");
				// intent.putExtra("title",tmpDto.intro);
				// getActivity().startActivity(intent);
				// } else {

				if (tmpDto.type == Constants.DiscoverProjectIntent) {
					intent = new Intent(getActivity(), ProjectDetailActivity.class);
					intent.putExtra("id", tmpDto.id);
					intent.putExtra("title", "项目详情");
					intent.putExtra("from", Constants.DETAIL_TYPE);
					intent.putExtra("position", position - 1);
					startActivity(intent);
				} else if (tmpDto.type == Constants.DiscoverMoneyIntent) {
					intent = new Intent(getActivity(), MoneyDetailActivity.class);
					intent.putExtra("id", tmpDto.id);
					intent.putExtra("title", "资金详情");
					intent.putExtra("from", Constants.DETAIL_TYPE);
					intent.putExtra("position", position - 1);
					startActivity(intent);
				}

				// }
			}
		});
	}

 
	
	 private void loadbanner() {
		 
		 String url="banner/topBannerList";
 		 ZrbRestClient.get(url, null, new AsyncHttpResponseHandler() {
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					CommonUtil.showToast(arg0, Discover_MainFragment.this.getActivity());
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// loadingview.Hide();
					String results = new String(arg2);
					try {
						Gson gson = new Gson();
						AdsDtoResult tmpDto = gson.fromJson(results, AdsDtoResult.class);
						if (tmpDto.res == 1) {
							if (tmpDto.data != null && tmpDto.data.size() > 0) {
								
								CommonUtil.InfoLog("results", results);
								initTop(tmpDto.data);
							 
							} else {
							 
								//CommonUtil.showToast("更多");
							}

						} else
							CommonUtil.showToast(tmpDto.msg, getActivity());
					} catch (Exception e) {
						CommonUtil.showToast(Discover_MainFragment.this.getString(R.string.error_serverdata_loadfail));
					}
				}
			});
	 }
	/*  mZrbRestClient = new ZrbRestClient(this.getActivity());
		;*/
	  

	private void initTop(final List<AdsDto> ads) {
 	    final Dynamic_banner_fragment fragment2 =(Dynamic_banner_fragment)this.getFragmentManager().findFragmentById(R.id.ads_banner);
	 	if(fragment2!=null){
 	 		mhandler.postDelayed(new Runnable(){
		 		   @Override
					public void run() {
		 			  fragment2.refleshUI(ads);
					}
		    }, 1000);
 	  	}
 	}
 
	
	@Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
		currentPage++;
		mhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				LoadData(mAdapter2.getMinIdTime(), false);
			}
		}, 400);

	}

	ZrbRestClient mZrbRestClient;
 	private void LoadData(long maxIdtime, final boolean isreflesh) {
		String url = String.format("dynamic/queryPage?limit=%1$s", 10);// &tradeDates=%2$s

		if (maxIdtime != -1)
			url += "&createTime=" + CommonUtil.formatlongDate(maxIdtime,dateformat);
		// CommonUtil.InfoLog("intention/list", url);
		if (mZrbRestClient == null) {
			mZrbRestClient = new ZrbRestClient(this.getActivity());
			mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

					CommonUtil.showToast(arg0, Discover_MainFragment.this.getActivity());
					if (currentPage > 1)
						msearchResults.hideloading();
					else
						msearchResults.onRefreshComplete();
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// loadingview.Hide();
					String results = new String(arg2);
					if (currentPage == 1){
						
						msearchResults.onRefreshComplete();
						loadbanner();
					} 
					else
						msearchResults.hideloading();
					 
 					try {
						Gson gson = new Gson();
						DynamicDtos tmpDto = gson.fromJson(results, DynamicDtos.class);
						if (tmpDto.res == 1) {
 							if (tmpDto.data != null && tmpDto.data.size() > 0) {
	 							mAdapter2.addAll(tmpDto.data,currentPage > 1);
	 							mAdapter2.notifyDataSetChanged();
							} else {
							 
								CommonUtil.showToast(String.format("暂无%1$s信息~~", currentPage == 0 ? "" : "更多"), getActivity());
							}

						} else
							CommonUtil.showToast(tmpDto.msg, getActivity());
					} catch (Exception e) {
						CommonUtil.showToast(Discover_MainFragment.this.getString(R.string.error_serverdata_loadfail));
					}
				}
			});
		}
		mZrbRestClient.getcheckSession(url);
	}

	private void firstLoad() {
		if (isFirstIn) {
			isFirstIn = false;
			 
			applyScrollListener();
			mhandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					msearchResults.setRefreshing(true);
				}
			}, 200);
		}
	}
 
	
	@Override
	public void onResume() {
		super.onResume();
		// 注册广播

		if (this.getUserVisibleHint())
			firstLoad();
	}

	private void applyScrollListener() {
		PauseOnScrollListener pauseOnScrollListener = new PauseOnScrollListener(ImageLoader.getInstance(), true, true);
		DiscoverListViewScrollListenerImpl listenerImpl = new DiscoverListViewScrollListenerImpl();
		listenerImpl.addScrollListener(pauseOnScrollListener);
		listenerImpl.addScrollListener(mListViewScrollListener);
		msearchResults.setOnScrollListener(listenerImpl);
	}

	/*
	 * 
	 * 
	 * 广播接收者的注册和接收
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
 
	}

	CollectionHelper mCollectionHelper;

	@Override
	public void onAttentionEvent(int postion) {
		// TODO Auto-generated method stub
		if (null == mCollectionHelper) {
			mCollectionHelper = new CollectionHelper(this.getActivity(), Constants.FocusIntent);
			mCollectionHelper.setOnCollectionListener(this);
		}

		 

	}

	@Override
	public void onCollectionEvent() {
		 
	}

	@Override
	public void showLoginDialog(String msg) {
  		
		 new AlertDialog(this.getActivity()).builder().setTitle("登录提示")
		   .setMsg(msg)
		   .setPositiveButton("马上登录", new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent1 = new Intent(Discover_MainFragment.this.getActivity(), User_phone_login.class);
				startActivity(intent1);
			}
		    }).setNegativeButton("取消").show();
	}

 

	protected void getData() {
		// 重新刷新数据
		// TODO Auto-generated method stub
		currentPage = 1;
		mhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				LoadData(-1, true);
				// msearchResults.setRefreshing(true);
			}
		}, 1000);

	}

	OnScrollListener mListViewScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			int pos = 0;
			if (firstVisibleItem == 0) {
				mTmptitle.setText(mFindStr);
				return;
			}
			if (firstVisibleItem > 0) {
				pos = firstVisibleItem - 1;
			}
			DynamicDto discoverDto = mAdapter2.getCurItem(pos);
			if (discoverDto != null) {
				String dateStr = TimeUtil.formatTime(discoverDto.createTime);
				String weekStr = TimeUtil.getWeek(discoverDto.createTime);
				mTmptitle.setText(dateStr + "  " + weekStr);
			}
		}
	};

 

 

}
